import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;

/**
 * Santa thread whose job is to sleep unless there is a group of elves who need
 * their problems fixed or a reindeer who wakes him up to start delivering
 * presents. Santa waits on the WinterHelperQueue, and responds as soon as there
 * is a WinterHelper(ElfGroup or Reindeer) in the queue.
 * 
 */
public class Santa extends Thread {

	private final CountDownLatch startSignal; // CountDownLatch so all the
												// threads start
												// at the same time

	/**
	 * Creates Santa and stores the start latch
	 */
	public Santa(CountDownLatch latch) {
		startSignal = latch;
	}

	/**
	 * Santa waits for something to enter WinterHelperQueue and helps whoever is
	 * at the front of the queue. Will call helpMe on the WinterHelper. If a
	 * reindeer, ready the sleigh.
	 */
	public void run() {

		try {
			// Wait for all threads to start
			startSignal.await();
		} catch (InterruptedException e) {

		}

		while (true) {
			WinterHelper currentHelper = null;
			WinterHelperQueue.getHelperQueue().lock.lock();
			try {

				// Await for a WinterHelper to enter the queue
				WinterHelperQueue.getHelperQueue().queueNotEmpty.await();

				currentHelper = WinterHelperQueue.getHelperQueue().take();

			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				WinterHelperQueue.getHelperQueue().lock.unlock();
			}

			try {
				if ((currentHelper != null)) {

					// If reindeer, ready the sleigh
					if (currentHelper.getClass().equals(Reindeer.class)) {

						System.out.println("Santa goes to the Sleigh.");
						
						// Notify the other reindeer to head to the sleigh
						currentHelper.helpMe();

						try {
							// Wait for everyone to reach the sleigh before
							// going on trip
							Sleigh.allReady.await();
						} catch (BrokenBarrierException e) {
							e.printStackTrace();
						}

						System.out
								.println("Santa has returned to the North Pole.");

					} else {
						// Else it's an elf. Just help.
						currentHelper.helpMe();
					}
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}